package dbinit;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import core.profile.model.BasicCredential;
import core.util.HibernateCoreUtil;

public class InitBasicCredential {
	
	public static Long doinit(String userId,String password,Long basicprofileId,int disabledflag,String passwordreminder,String reminderemail,Long securityquestion,String answer,int failurecount)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		BasicCredential basiccredential = new BasicCredential();
		basiccredential.setUserId(userId);
		// MD5 algorithm  to encript the password
		String toEnc = password ; // Value to encrypt  
		MessageDigest mdEnc = null;
		try {
			mdEnc = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // Encryption algorithm  
          
		mdEnc.update(toEnc.getBytes(), 0, toEnc.length());  
		String md5Password = new BigInteger(1, mdEnc.digest()).toString(16) ;// Encrypted password
		basiccredential.setPassword(md5Password);
		basiccredential.setSecurityquestion(InitSecurityQuestion.getSecurityQuestionByUuid(securityquestion));
		basiccredential.setBasicprofile(InitBasicProfile.getBasicProfileByUuid(basicprofileId));
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
		    uuid = (Long)session.save(basiccredential);
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return uuid ;
	}
}
